package com.dycong.common.leetcode.any;

import java.util.ArrayList;
import java.util.List;

/**
 * 作用描述:就是给一个整数5插入到任何一个数中，可以插入到任何一个位置，保证被插入这个数最大
 *
 * @author dycong
 * @date 2019/12/19 11:57
 */
public class InsertFive {
    public static void main(String[] args) {
        InsertFive insertFive = new InsertFive();
        System.out.println(insertFive.insert(268));
        System.out.println(insertFive.insert(670));
        System.out.println(insertFive.insert(0));
        System.out.println(insertFive.insert(-999));
    }

    public int insert(int num) {
        int pn = num >= 0 ? 1 : -1;
        num = Math.abs(num);
        List<Integer> list = new ArrayList<>(10);
        if (num == 0) {
            list.add(0);
        }
        while (num != 0) {
            list.add(num % 10);
            num /= 10;
        }
        for (int i = list.size() - 1; i >= 0; i--) {
            if (pn == 1 && list.get(i) < 5) {
                list.add(i + 1, 5);
                break;
            }
            if (pn == -1 && list.get(i) > 5) {
                list.add(i + 1, 5);
                break;
            }
        }
        int aws = 0;
        int base = 1;
        for (Integer integer : list) {
            int step = integer * base;
            aws = aws + step;
            base *= 10;
        }

        return aws * pn;
    }
}
